﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Web;
using BluePortal.Medias.Core;

namespace BluePortal.QuikStart.Images
{
    public class ThumbnailHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            if(context.Request["vid"]!=null)
            {
                try
                {
                    Guid vid = new Guid(context.Request["vid"]);
                    context.Response.ContentType = "image/jpeg";
                    context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(600));
                    context.Response.Cache.SetCacheability(HttpCacheability.Public);
                                        
                    if (context.Request["chaptertime"] != null)
                    {
                        //Return thumbnail chapter
                        IEnumerable<VideoChapter> videoChapters = new BCVideoChapter().FindByVideo(vid);
                        VideoChapter videoChapter = null;
                        foreach (VideoChapter vc in videoChapters)
                        { 
                            TimeSpan ts = new TimeSpan(vc.Time);
                            TimeSpan rts = System.TimeSpan.Parse(context.Request["chaptertime"]);

                            if (Math.Abs(ts.Subtract(rts).TotalSeconds) < 0.01)
                            {
                                videoChapter = vc;
                                break;
                            }
                        }
                        context.Response.OutputStream.Write(videoChapter.Image, 0, videoChapter.Image.Length);
                    }
                    //Return thumbnail video
                    else
                    {
                        BCMedia bc = new BCMedia();
                        bc.Context.DeferredLoadingEnabled = true;
                        Media v = bc.FindByID(vid);
                        context.Response.OutputStream.Write(v.Preview, 0, v.Preview.Length);
                    }
                }
                catch
                {
                    System.Drawing.Image bmnull = Bitmap.FromFile(context.Server.MapPath("~/Images/miscellaneous.jpg"));
                    bmnull.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
        }

        private object TimeSpan(long p)
        {
            throw new NotImplementedException();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
